<template>
  <div>
    <van-uploader
      v-model="fileList"
      v-bind="$attrs"
      :previewSize="previewSize"
      :beforeRead="beforeRead"
      :afterRead="afterRead"
      :accept="accept"
    >
    </van-uploader>
    <div v-if="tips" class="tips">{{ tips }}</div>
  </div>
</template>

<script setup name="i-uploader">
import { showToast } from 'vant'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {}
  },
  previewSize: {
    type: [Number, String],
    default: '80px'
  },
  maxSize: {
    type: Number,
    default: 50 * 1024 * 1024 // 50M
  },
  accept: {
    type: String,
    default: ''
  },
  tips: {
    type: String,
    default: ''
  }
})
const fileList = ref(props.modelValue)
const beforeRead = (file) => {
  if (props.maxSize && file.size > props.maxSize) {
    showToast(`单个附件最大不能超过${props.maxSize / 1024 / 1024}M，请重新选择`)
    return false
  }
  if (props.accept && !props.accept.includes('.' + file.type.split('/')[1])) {
    showToast('请检查上传文件格式')
    return false
  }
  return true
}
const afterRead = (file) => {
  file.status = 'uploading'
  file.message = '上传中...'
  setTimeout(() => {
    file.status = 'done'
  }, 1000)
}
</script>

<style scoped>
.tips {
  color: #ccc;
  margin-top: 8px;
  font-size: 12px;
}
</style>